package com.example.config;

import com.example.handler.SecurityAccessDeniedHandler;
import com.example.handler.SecurityAuthenticationEntryPoint;
import com.example.rsa.InMemoryRsaKeyPairRepository;
import com.example.rsa.RsaKeyPairJWKSource;
import com.example.rsa.RsaKeyPairJWKTokenCustomizer;
import com.example.rsa.RsaKeyPairRepository;
import com.example.security.InfoDetail;
import com.example.security.UserDetail;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.*;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Configuration
public class JwkConfig {

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new SecurityAccessDeniedHandler();
    }

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new SecurityAuthenticationEntryPoint();
    }

    /**
     * 配置 OAuth2Token 的生成器
     * @param jwtEncoder
     * @param customizer
     * @return
     */
    @Bean
    public OAuth2TokenGenerator<OAuth2Token> oAuth2TokenGenerator(JwtEncoder jwtEncoder, OAuth2TokenCustomizer<JwtEncodingContext> customizer) {
        JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder);
        jwtGenerator.setJwtCustomizer(customizer);
        OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
        OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
        return new DelegatingOAuth2TokenGenerator(jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    }

    /**
     * 一个 UserDetailsService 实例，用于检索用户进行身份验证
     */
//    @Bean
//    public UserDetailsService userDetailsService() {
//        UserDetails userDetails = User.withUsername("abc")
//                .password(passwordEncoder().encode("abc"))
//                .roles("USER")
//                .username("admin")
//                //admin/admin
//                .password("$2a$10$3aWK8etrmDjaa/93IB5kGeMNfwX/NsInqxMPp7BKb5HRxISnAjCdK")
//                .roles("USER")
//                .authorities(List.of(new SimpleGrantedAuthority("sys.user.page")))
//                .build();
//        return new InMemoryUserDetailsManager(userDetails);
////        return new JdbcUserDetailsManager(DataSource dataSource);
//    }


    /**
     * JWK 设置端点
     *
     * <p>
     * 用于对访问令牌进行签名的 com.nimbusds.jose.jwk.source.JWKSource 实例
     *
     * @return
     */
    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }

    /**
     * ava.security.KeyPair 的实例，其中包含启动时生成的密钥，
     *
     * @return
     */
    private static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }
    /**
     * 用于解码已签名访问令牌的 JwtDecoder 实例。
     * 在 OAuth2 客户端身份验证期间对 Jwt Bearer Token 进行身份验证。
     * 一种方便的方法来为 OAuth2 授权服务器应用最低默认配置。
     *
     * @param jwkSource
     * @return
     */
    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }
    /**
     * 配置JwtEncoder
     *
     * @param jwkSource
     * @return
     */
    @Bean
    public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
        return new NimbusJwtEncoder(jwkSource);
    }


    /**
     * @return
     * @Bean将自动配置 JwtGenerator
     */
    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
        return context -> {
//            JwsHeader.Builder headers = context.getJwsHeader();
//            JwtClaimsSet.Builder claims = context.getClaims();
            if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
                Authentication authentication = context.getPrincipal();
                if (authentication.getPrincipal() instanceof UserDetail userDetail) {
                    InfoDetail infoDetail = new InfoDetail();
                    infoDetail.setId(userDetail.getId());
                    infoDetail.setDeptId(userDetail.getDeptId());
                    infoDetail.setUsername(userDetail.getUsername());
                    infoDetail.setStoreId(userDetail.getStoreId());
                    infoDetail.setTenantId(userDetail.getTenantId());
                    infoDetail.setIsSuperTenant(userDetail.getIsSuperTenant());
                    infoDetail.setIsHeadStore(userDetail.getIsHeadStore());
                    infoDetail.setIsBusinessUser(userDetail.getIsBusinessUser());
                    context.getClaims().claim("infoDetail", infoDetail);
                    // jwt中保存权限，在资源服务器中，使用权限转换器来获取，权限生效
                    List<String> collect = userDetail.getAuthorities().stream().map(GrantedAuthority::getAuthority).distinct().collect(Collectors.toList());
                    // 角色待补充
//                    context.getClaims().claim("roles", collect);
                    Set<String> authorizedScopes = context.getAuthorizedScopes();
                    collect.addAll(authorizedScopes);
                    context.getClaims().claim("authorities", collect);
                } else {
//                    OAuth2AuthenticationToken authentication1 = (OAuth2AuthenticationToken) authentication;
//                    String authorizedClientRegistrationId = authentication1.getAuthorizedClientRegistrationId();
//                    if ("gitee".equals(authorizedClientRegistrationId)){
//                        OAuth2User principal = authentication1.getPrincipal();
//                        Map<String, Object> attributes = principal.getAttributes();
//                        String username = (String) attributes.get("name");
//                        InfoDetail infoDetail = new InfoDetail();
//                        infoDetail.setId(null);
//                        infoDetail.setDeptId(null);
//                        infoDetail.setUsername(username);
//                        context.getClaims().claim("infoDetail", infoDetail);
//                        // jwt中保存权限，在资源服务器中，使用权限转换器来获取，权限生效
//                        List<String> collect = principal.getAuthorities().stream().map(GrantedAuthority::getAuthority).distinct().collect(Collectors.toList());
//                        // 角色待补充
////                    context.getClaims().claim("roles", collect);
//                        Set<String> authorizedScopes = context.getAuthorizedScopes();
//                        collect.addAll(authorizedScopes);
//                        context.getClaims().claim("authorities", collect);

//                    }
                }

            } else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
                // Customize headers/claims for id_token

            }
        };
    }


    /**
     * 用于管理客户端的 RegisteredClientRepository 实例。
     *
     * @param jdbcTemplate
     * @return
     */
    @Bean
    public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
        return new JdbcRegisteredClientRepository(jdbcTemplate);
    }

    /**
     * OAuth2AuthorizationService 是一个中心组件，新的授权被存储，现有的授权被查询。
     * 当遵循特定的协议流程时，它被其他组件使用例如，客户端认证、授权许可处理、令牌内省、令牌撤销、动态客户端注册等。
     *
     * @param jdbcTemplate
     * @return
     */
    @Bean
    public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate) {
        return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository(jdbcTemplate));
    }

    /**
     * OAuth2AuthorizationConsentService 是一个中心组件，新的授权同意被存储，现有的授权同意被查询。
     * 它主要被实现OAuth2授权请求流程的组件使用，例如：authorization_code grant
     *
     * @param jdbcTemplate
     * @return
     */
    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate) {
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository(jdbcTemplate));
    }
}
